package com.lhf.azkaban.springbatch.example.batchreader;

import com.lhf.azkaban.springbatch.example.mode.RepayOrderInfo;
import com.lhf.azkaban.springbatch.example.utils.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.batch.core.ItemReadListener;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.LineCallbackHandler;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;

/**
 * @Author:95780
 * @Date: 17:46 2019/11/20
 * @Description: Flat文件格式读取类  实现了分隔符和json格式
 */
@Service
//@StepScope
public class RepayOrderFlatFileItemReader<T> extends FlatFileItemReader implements ItemReadListener {

    private static final Logger logger = LogManager.getLogger(RepayOrderFlatFileItemReader.class);

    @Value("${repay.orders.bigpath}")
    private String bigpath;
    @Value("${repay.orders.bigname}")
    private String bigname;
    @Value("${repay.orders.outpath}")
    private String outpath;
    @Value("${repay.orders.outname}")
    private String outname;
//    @Value("#{jobParameters[jobname]}")
//    private String jobname;
//    @Value("#{jobParameters[jobpath]}")
//    private String jobpath;

    public RepayOrderFlatFileItemReader() {
        logger.info("======RepayOrderFlatFileItemReader Begin ======   time:   " + DateUtil.parseDateTime(LocalDateTime.now(), DateUtil.PATTERN_DEFAULT_DATA));
        repayOrderOfDelimitedLine();
    }

    @Override
    protected void doOpen() throws Exception {
//        logger.info("=======================================================");
//        logger.info("=======================================================");
//        logger.info("=======================================================");
//        logger.info("RepayOrderProcessor   ======= jobname " + jobname);
//        logger.info("RepayOrderProcessor   ======= jobpath " + jobpath);
//        logger.info("+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+");
//        logger.info("+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+");
//        logger.info("+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+");
        File pathFile = new File(bigpath);
        if (!pathFile.exists()) {
            throw new Exception("文件路径不存在,路径:" + bigpath);
        }
        String[] fileNames = pathFile.list(); //获取该路径下所有的文件名称
        if (fileNames == null && fileNames.length <= 0) {
            throw new Exception("文件" + bigname + "不存在,路径:" + bigpath);
        }
        String filePath = "";
        for (String fileName : fileNames) {
            if (fileName.startsWith(bigname)) { /*repay-orders-big.dat*/
                filePath = bigpath + File.separator + fileName;
            }
        }
        setResource(new PathResource(filePath));
        super.doOpen();
    }

    /**
     * 分隔符文件读取配置
     */
    private void repayOrderOfDelimitedLine() {
        setLineMapper(new DefaultLineMapper<RepayOrderInfo>() {{
            setLineTokenizer(new DelimitedLineTokenizer("|") {{  //一行内容分割默认用','分割
                setNames(new String[]{"userId", "productId", "contractNo", "amount", "repayType", "repayMethod"});
                setComments(new String[]{"==", "##"});  //# 为默认的注释符号
//                setLinesToSkip(1);//跳过第一行
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<RepayOrderInfo>() {{
                setTargetType(RepayOrderInfo.class);
            }});
            setSkippedLinesCallback(new LineCallbackHandler() {
                @Override
                public void handleLine(String s) {
                    logger.error("RepayOrderFlatFileItemReader skip line:" + s);
                }
            });
        }});

    }

    @Override
    public void beforeRead() {
        logger.info("======ItemReadListener beforeRead======");
    }
    @Override
    public void afterRead(Object o) {
        logger.info("======ItemReadListener afterRead======");
        logger.info(o);
    }
    @Override
    public void onReadError(Exception e) {
        logger.info("======ItemReadListener onReadError======");
    }
}
